﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;

namespace GoodStuff.Silverlight
{
    /// <remarks>
    /// Courtesy of Rob Eisenberg
    /// http://live.visitmix.com/MIX10/Sessions/EX15
    /// </remarks>    
    public class ResultEnumerator
    {
        private IEnumerator<IResult> _enumerator;

        public ResultEnumerator(IEnumerable<IResult> children)
        {
            _enumerator = children.GetEnumerator();
        }

        public void Enumerate()
        {
            ChildCompleted(null, EventArgs.Empty);
        }

        private void ChildCompleted(object sender, EventArgs args)
        {
            var previous = sender as IResult;
            if (previous != null)
            {
                previous.Completed -= ChildCompleted;
            }

            if (!_enumerator.MoveNext())
            {
                return;
            }

            var next = _enumerator.Current;
            next.Completed += ChildCompleted;
            next.Execute();
        }
    }
}
